package com.swj.common.security.handler;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.swj.common.core.context.SecurityContextHolder;
import com.swj.common.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


@Slf4j
@Component
public class FieldAutoFilledHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {

        String currentUserName = SecurityUtil.getUsername();

        LocalDateTime now = LocalDateTime.now();
        String time=now.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒"));
        String simpleTime=now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        log.info("开始自动插入字段....,当前时间:{}",time);
        log.info("当前用户名称:{}", JSON.toJSONString(currentUserName));

        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, now);
        log.info("自动插入字段创建时间:{}",simpleTime);

        this.strictInsertFill(metaObject, "createBy", String.class,currentUserName);
        log.info("自动插入字段创建者:{}",currentUserName);

        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, now);
        log.info("自动插入字段更新时间:{}",simpleTime);

        this.strictInsertFill(metaObject, "updateBy", String.class,currentUserName);
        log.info("自动插入字段更新者:{}",currentUserName);
    }

    @Override
    public void updateFill(MetaObject metaObject) {

        String currentUserName = SecurityContextHolder.getUserName();

        LocalDateTime now = LocalDateTime.now();
        String time=now.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒"));
        String simpleTime=now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        log.info("开始自动更新字段 ....,当前时间:{}",time);

        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, now);
        log.info("自动插入字段更新时间:{}",simpleTime);

        this.strictUpdateFill(metaObject, "updateBy", String.class,currentUserName);
        log.info("自动插入字段更新者:{}",currentUserName);
    }
}
